package com.javaee.term.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javaee.term.Enums.PrintStatusEnum;
import com.javaee.term.dto.ContactDetailDto;
import com.javaee.term.dto.ProductDto;
import com.javaee.term.exception.HandException;
import com.javaee.term.form.ContactForm;
import com.javaee.term.form.SendProductForm;
import com.javaee.term.model.*;
import com.javaee.term.service.*;
import com.javaee.term.split.ContactFormConver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * author 陈伯瑞
 * date 2019/12/15 0015 13:43
 * version 1.0
 **/
@Controller
@RequestMapping("/seller/contact")
@Slf4j
public class ContactController {

    @Autowired
    private ContactService contactService;
    @Autowired
    private ContactDetailService contactDetailService;

    @Autowired
    private ProductService productService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SalemanService salemanService;
    @Autowired
    private  SendProductService sendProductService;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size,
                             Map<String, Object> map) {

  /*    动态sql实现实现分页
        Map<String, Object> data = new HashMap();
        data.put("currIndex", (page-1)*size);
        data.put("pageSize", size);
        List<Contact> contactsInfolist= contactService.findByPage(data);*/

        /* 插件实现分页*/
        PageHelper.startPage(page, size);
        List<Contact> list = contactService.findAll();
        PageInfo<Contact> contactsInfoPage = new PageInfo<Contact>(list);
        map.put("contactsInfoPage", contactsInfoPage);
        map.put("currentPage", page);
        map.put("size", size);
        map.put("totalpage", contactsInfoPage.getPages());
        return new ModelAndView("contact/list", map);
    }
    @GetMapping("/detail")
    public ModelAndView detail(@RequestParam(value = "contactId") String contactId,
                             Map<String, Object> map){
        ContactDetailDto contactDetailDto=contactDetailService.findContactDetail(contactId);
        List<SendProductList> sendByContactId = sendProductService.findSendByContactId(contactId);
        map.put("sendProductList",sendByContactId);
        map.put("contactDetailDto",contactDetailDto);
        return new ModelAndView("contact/detail", map);
    }
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "contactId", required = false) String contactId,
                              Map<String, Object> map) {
        if (!StringUtils.isEmpty(contactId)) {
            ContactDetailDto contactInfo=contactDetailService.findContactDetail(contactId);
            map.put("contactInfo", contactInfo);
        }
        List<Product> productList=productService.findAll();
        List<SaleMan>  saleManList=salemanService.findAll();
        List<Customer>  customerList=customerService.findAll();
        map.put("productList", productList);
        map.put("saleManList", saleManList);
        map.put("customerList", customerList);
        return new ModelAndView("contact/index", map);
    }

    @PostMapping("/save")
    @Transactional
    public ModelAndView save(@Valid ContactForm contactForm,
                             BindingResult bindingResult, Map<String, Object> map) {
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/contact/index");
            return new ModelAndView("common/error", map);
        }
        ContactFormConver contactFormConver=new ContactFormConver();
        List<Product> products=productService.findAll();
        Contact contact=contactFormConver.fromToContact(contactForm,products);
        List<ContactDetail> newContactDetails=contactFormConver.fromToContactDetail(contactForm,contact.getContactId());

        try {
            //如果contactform.contactid为空, 说明是新增,else为修改
            if (contactForm.getContactId().isEmpty()) {
                //修改create时间和update时间,合同表插入
                contact.setCreateTime(new Date());
                contact.setUpdateTime(new Date());
                contactService.insert(contact);
                //合同详情表插入
                for(ContactDetail newContactDetail:newContactDetails){
                    newContactDetail.setCreateTime(new Date());
                    newContactDetail.setUpdateTime(new Date());
                    contactDetailService.insert(newContactDetail);
                }
            } else {
                //create时间不变，修该update时间，合同表更新
                contact.setCreateTime(contactService.findOne(contact.getContactId()).getCreateTime());
                contact.setUpdateTime(new Date());
               contactService.update(contact);
               //合同详情表更新
             List<ContactDetail> pastContactDetails=contactDetailService.findDetails(contact.getContactId());
                for(ContactDetail pastContactDetail:pastContactDetails){
                       contactDetailService.delete(pastContactDetail.getDetailId());
                   }

                for(ContactDetail newContactDetail:newContactDetails){

                    for(ContactDetail pastContactDetail:pastContactDetails){
                        if(newContactDetail.getDetailId().equals(pastContactDetail.getDetailId())){
                            newContactDetail.setCreateTime(pastContactDetail.getCreateTime());
                        }
                    }
                    if(newContactDetail.getCreateTime()==null){
                        newContactDetail.setCreateTime(new Date());
                    }
                    newContactDetail.setUpdateTime(new Date());
                    contactDetailService.insert(newContactDetail);
                  }
            }
        } catch (HandException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/contact/list");
            return new ModelAndView("common/error", map);
        }
        map.put("url", "/sell/seller/contact/list");
        return new ModelAndView("common/success", map);
    }
    @GetMapping("/send/index")
    public ModelAndView sendIndex(@RequestParam(value = "contactId", required = false) String contactId,
                                  @RequestParam(value = "productId", required = false) String productId,

                                  Map<String, Object> map) {
        if (!StringUtils.isEmpty(contactId)) {
            ContactDetailDto contactInfo=contactDetailService.findContactDetail(contactId);
            map.put("contactId", contactInfo.getContactId());
            map.put("productId",productId);
            try {
                for (ProductDto productDto : contactInfo.getProductDtos())
                    if (productDto.getProductId().equals(productId)) {
                        map.put("productNumout", productDto.getNotout());
                        map.put("productName",productDto.getProductName());
                        return new ModelAndView("contact/sendProduct", map);
                    }
                throw  new HandException(0,"商品确认发货异常") ;
            }catch (HandException e) {
                map.put("msg", e.getMessage());
                map.put("url", "/sell/seller/contact/detail?contactId="+contactId);
                return new ModelAndView("common/error", map);
            }

        }
        map.put("msg","操作异常");
        map.put("url", "/sell/seller/contact/list");
        return new ModelAndView("common/error", map);
    }
    @PostMapping("/send/save")
    @Transactional
    public ModelAndView sendsave(@Valid SendProductForm sendProductForm,
                             BindingResult bindingResult,
                             Map<String, Object> map) {
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/contact/detail?contactId="+sendProductForm.getContactId());
            return new ModelAndView("common/error", map);
        }
        try {
            sendProductService.updateQuantityByContactProduct(sendProductForm.getContactId(),
                    sendProductForm.getProductId(),
                    sendProductForm.getProductQuantity());
            //每次更新发货单后判断当前的合同商品详情状态
            List<SendProductList> sendProductLists= sendProductService.findByContactIdAndProductId(sendProductForm.getContactId(),
                    sendProductForm.getProductId());
            Integer allOut = sendProductLists.stream().mapToInt(SendProductList::getProductQuantity).sum();
            ContactDetail contactDetail=contactDetailService.findByContactProduct(sendProductForm.getContactId(),
                    sendProductForm.getProductId());

            contactDetail.setPrintStatus(PrintStatusEnum.UNFINISH.getCode());
            if(allOut.equals(contactDetail.getProductQuantity())){
                contactDetail.setPrintStatus(PrintStatusEnum.FINISH.getCode());
            }
            contactDetailService.update(contactDetail);
        } catch (HandException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/contact/detail?contactId="+sendProductForm.getContactId());
            return new ModelAndView("common/error", map);
        }
        map.put("url", "/sell/seller/contact/detail?contactId="+sendProductForm.getContactId());
        return new ModelAndView("common/success", map);
    }
}
